package com.imu.wys;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.core.ResolvableType;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ApplicationContext {

    Map<String, Object> beans = new HashMap<String, Object>();


    public ApplicationContext(String path) throws Exception {
        // 创建saxReader对象
        SAXReader reader = new SAXReader();
        // 通过read方法读取一个文件 转换成Document对象
        Document document = reader.read(new File(path));
        // 获取根节点元素对象
        Element node = document.getRootElement();
        // beans下的节点
        List<Element> list = node.elements();
        for (Element bean : list) {
            String id = bean.attributeValue("id");
            String className = bean.attributeValue("class");
            Object o = Class.forName(className).newInstance();
            //将对象放入容器中
            beans.put(id, o);

            Iterator<Element> it = bean.elementIterator();
            //遍历bean下面的子节点
            while (it.hasNext()) {
                Element propertyElement = it.next();
                String propertyName = propertyElement.attributeValue("name");
                String propertyRef = propertyElement.attributeValue("ref");
                String propertyValue = propertyElement.attributeValue("value");

                Object beanObject=null;
                if(propertyRef!=null) {
                    //获取从map中获取需要注入的对象
                    beanObject = beans.get(propertyRef);
                }
                String methodName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                Method method = null;
                //如果是注入普通的属性值
                if (propertyValue != null) {
                    Field field = o.getClass().getDeclaredField(propertyValue);
                    method = o.getClass().getMethod(methodName,field.getType());
                    method.invoke(o, propertyValue);
                }
                //注入对象
                else {

                    Field field = o.getClass().getDeclaredField(propertyRef);  //根据参数  获得这个名字的成员变量
                    method = o.getClass().getMethod(methodName,field.getType());
                    method.invoke(o, beanObject);
                }
            }
        }

    }

    public Object getBean(String s) throws BeansException {
        return beans.get(s);
    }


}
